<template>
  <view class="tips">
    <image class="img" src="@/static/images/alert_icon.png" mode="widthFix"></image>
    <view>合同生成后，修改租车费/续租费/换车费/租车押金/违章押金后，不影响已发起签署的合同金额。 </view>
  </view>
  <view class="detail-container" :style="'height: calc(100vh - ' + barHeight * 2 + 'rpx)'">
    <!-- 调试维护弹窗使用 👇 -->
    <!-- <view @click="maintenancesShow">123</view> -->
    <!-- <scroll-view scroll-y :scroll-with-animation="true" :enable-back-to-top="true" refresher-background="#f7f8fa"> -->
    <view>
      <ve-card
        :title="'合同编号：' + (record.contractNo || '-')"
        :sub-title="record.contractStatusName"
        :type="
          record.contractStatus == 1 || record.contractStatus == -2
            ? 'gray'
            : record.contractStatus == 2
            ? 'blue'
            : record.contractStatus == 3 || record.contractStatus == 10
            ? 'green'
            : record.contractStatus == 4 ||
              record.contractStatus == 5 ||
              record.contractStatus == 6 ||
              record.contractStatus == 7 ||
              record.contractStatus == 8 ||
              record.contractStatus == 11 ||
              record.contractStatus == -1
            ? 'pink'
            : record.contractStatus == 9
            ? 'purple'
            : 'gray'
        "
        v-for="(record, index) in dataSource"
        :key="record.contractStatus"
      >
        <ve-cell label="创建方式">{{ record.createWayName || '-' }}</ve-cell>
        <ve-cell label="创建节点">{{ record.createWay == '2' ? '-' : record.createNode || '-' }}</ve-cell>
        <ve-cell label="合同类型">{{ record.contractTypeName || '-' }}</ve-cell>
        <ve-cell label="合同模板名称">{{ record.templateName || '-' }}</ve-cell>
        <ve-cell label="归属门店">{{ record.siteName || '-' }}</ve-cell>
        <!-- 签署中 -->
        <block v-if="record.contractStatus == 2 || record.contractStatus == 3 || record.contractStatus == 8">
          <ve-cell label="承租方" class="tag-person">
            <view class="fs30 fw400 c1">{{ record.leaseType == 1 ? record.lesseeCompanyName || '-' : record.lesseeName || '-' }}</view>
            <view class="person-flex-copy" v-if="record.lesseeSignStatusName">
              <view :class="['tag', record.lesseeSignStatus == 1 ? 'text-no' : 'text-yes']">{{ record.lesseeSignStatusName || '-' }}</view>
            </view>
            <view class="copys" @click="copylink(record, 2)" v-if="hasPermission('contractCopySigningLink')">
              <image class="image-icon" src="@/static/icons/link.png" mode="widthFix"></image>
              <view class="copy-text">复制合同链接</view>
            </view>
          </ve-cell>
          <ve-cell label="出租方" class="tag-person">
            <view class="fs30 fw400 c1">{{ record.tenantName || '-' }}</view>
            <view class="person-flex-copy" v-if="record.hireSignStatusName">
              <view :class="['tag', record.hireSignStatus == 1 ? 'text-no' : 'text-yes']">{{ record.hireSignStatusName || '-' }}</view>
            </view>
          </ve-cell>
        </block>
        <!-- 作废中 -->
        <block v-if="record.contractStatus == 7">
          <ve-cell label="承租方" class="tag-person">
            <view class="fs30 fw400 c1">{{ record.leaseType == 1 ? record.lesseeCompanyName || '-' : record.lesseeName || '-' }}</view>
            <view class="person-flex-copy" v-if="record.lesseeInvalidedStatusName">
              <view :class="['tag', record.lesseeInvalidedStatus == 1 ? 'text-no' : 'text-yes']">{{
                record.lesseeInvalidedStatusName || '-'
              }}</view>
            </view>
            <view
              class="copys"
              @click="copylink(record, 7)"
              v-if="record.contractStatus == 7 && record.lesseeInvalidedStatus == 1 && hasPermission('contractCopyVoidLink')"
            >
              <image class="image-icon" src="@/static/icons/link.png" mode="widthFix"></image>
              <view class="copy-text">复制作废链接</view>
            </view>
          </ve-cell>
          <ve-cell label="出租方" class="tag-person">
            <view class="fs30 fw400 c1">{{ record.tenantName || '-' }}</view>
            <view class="person-flex-copy" v-if="record.hireInvalidedStatusName">
              <view :class="['tag', record.hireInvalidedStatus == 1 ? 'text-no' : 'text-yes']">{{
                record.hireInvalidedStatusName || '-'
              }}</view>
            </view>
          </ve-cell>
        </block>
        <ve-cell label="发起人">{{ record.startPersonName || '-' }}</ve-cell>
        <ve-cell label="发起签署时间">{{ record.startTime || '-' }}</ve-cell>
        <ve-cell label="发起节点">{{ record.startNode || '-' }}</ve-cell>
        <ve-operate-list :operates="operates" :record="record" />
        <ve-popup :model-value="popupValue" @close="close" mode="bottom" :maskClose="true">
          <view class="add-popup">
            <view class="title">请选择</view>
            <ve-button class="button" size="default" @click="toPreview(currenRecord)" style="margin-bottom: 32rpx; background: #d5e3ff"
              >下载PDF文件</ve-button
            >
            <ve-button class="button" size="default" @click="toDownload(currenRecord)">下载JPG图片(合成长图)</ve-button>
          </view>
        </ve-popup>
      </ve-card>
      <!-- 加载结束列表为空时展示 -->
      <ve-empty v-if="dataSource.length == 0"></ve-empty>
    </view>
    <!-- </scroll-view> -->
    <ve-bottom-box v-if="handContractPermission">
      <ve-button type="primary" @click="showContract" style="width: 100%">手动生成电子合同</ve-button>
    </ve-bottom-box>
    <!-- 填写电话 -->
    <addPhoneModal ref="addphone" @ok="addphoneFn" />
    <!-- 维护 -->
    <maintenanceContract ref="maintenances" @ok="maintenanceFn" />
    <!-- 复制弹窗 -->
    <copyModal ref="copymodals" />
  </view>
</template>

<script setup>
  import { usePermission } from '@/hooks/usePermission'
  import { ref } from 'vue'
  import { onShow } from '@dcloudio/uni-app'
  import { appConfig } from '@/config/index.js'
  import addPhoneModal from '@/pages/order/components/customer/add-phone.vue'
  import maintenanceContract from '@/pages/order/components/customer/maintenance-contract.vue'
  import copyModal from '@/pages/order/components/customer/copy-modal.vue'
  import useList from '@/hooks/useList'
  import { shortorderdetail } from '@/api/dict/detail'
  import { getOrdrDetailsAPI } from '@/api/order/lOrder'
  import { clientInfoDetail, editClientInfo } from '@/api/market/member'
  import {
    downloadContractFileAPI,
    invalidAPI,
    initiateAPI,
    getTenantSignUrlAPI,
    revokeAPI,
    nullifyAPI,
    determineAPI,
    getLesseeSignUrlAPI,
    dzcontractAPI,
    czcontractAPI,
    deleteContractFileAPI,
    createQysContractAPI,
  } from '@/api/order/contract'
  import { userStore } from '@/stores'
  const baseURL = appConfig.apiBaseUrl
  console.log(appConfig.env)
  console.log(getApp().globalData.requestUrl)
  const barHeight = ref(0)
  const addphone = ref(null)
  const maintenances = ref(null)
  const copymodals = ref(null)
  const orderCode = ref()
  const clientData = ref()
  const dataSource = ref([])
  const popupValue = ref(false)
  const isDownload = ref(false)
  const props = defineProps({
    orderId: [String, Number],
    orderType: {
      type: String,
      default: '2', //  2短租 3长租
    },
    // 合同付费类型
    contractPayType: {
      type: Number,
      default: 0,
    },
    permissionPrefix: String,
  })

  // 是否有对应按钮权限
  const hasPermission = (permissionSubfix) => {
    const permission = props.permissionPrefix + '.' + permissionSubfix
    return usePermission(permission)
  }

  // 完整权限字符串
  const getPermission = (permissionSubfix) => {
    return props.permissionPrefix + '.' + permissionSubfix
  }

  const handContractPermission = ref(false)
  const userInfoStore = userStore()
  userInfoStore.setEpDetail().then((res) => {
    let val = res.config
    console.log(usePermission('svmsapp:order:short-order.handContract'), '短租权限')
    console.log(usePermission('svmsapp:order:long-order.handContract'), '长租权限')
    console.log(val, '测试权限')
    if (val.userEcontractEnabled == 1) {
      if (val.userContractServiceType.includes(0) && props.orderType == 2) {
        console.log('有短租权限')
        handContractPermission.value = hasPermission('handContract')
      } else if (val.userContractServiceType.includes(1) && props.orderType == 3) {
        console.log('有长租权限')
        handContractPermission.value = hasPermission('handContract')
      }
    }

    handleOpenNewContract()
  })
  // 查询参数
  const queryParam = ref({})
  const loadData = () => {
    if (props.orderType == 2) {
      queryParam.value.payType = props.contractPayType
      dzcontractAPI(queryParam.value).then((res) => {
        dataSource.value = res.result
      })
    } else {
      queryParam.value.contractAttribute = props.contractPayType
      czcontractAPI(queryParam.value).then((res) => {
        dataSource.value = res.result
      })
    }
  }
  const resetRefresh = () => {
    loadData()
  }
  // 订单信息
  const orderInfo = ref({})
  // 初始化
  const init = (callback) => {
    if (props.orderId) {
      if (props.orderType == 2) {
        shortorderdetail({ id: props.orderId }).then((res) => {
          orderCode.value = res.result.orderInfo.orderCode
          queryParam.value = {
            orderId: props.orderId,
            orderCode: orderCode.value,
            orderType: 1,
            payType: 1,
          }
          if (orderCode.value) {
            loadData()
          }
          orderInfo.value = res.result.orderInfo

          callback && callback()
        })
      } else {
        queryParam.value = {
          orderId: props.orderId,
          orderType: 2,
          pageSize: 10,
          contractAttribute: 1,
        }
        loadData()
        getOrdrDetailsAPI({ id: props.orderId }).then((res) => {
          orderInfo.value = res.result.orderInfo

          callback && callback()
        })
      }
    }
  }
  // 触发新增电子合同
  const handleOpenNewContract = () => {
    // 是否有新增电子合同的按钮权限
    let tempPermission = false
    if (userInfoStore.enterpriseDetail && Object.keys(userInfoStore.enterpriseDetail).length > 0) {
      // 商户详情获取，判断按钮权限
      tempPermission = handContractPermission.value
    }
    // 详情是否获取完毕
    let detailGetted = false
    if (orderInfo.value && Object.keys(orderInfo.value).length > 0) {
      detailGetted = true
    }
    // 有按钮权限并且详情获取完毕
    if (tempPermission && detailGetted) {
      const triggerNewContract = uni.getStorageSync('triggerNewContract')
      if (triggerNewContract === 1) {
        uni.removeStorageSync('triggerNewContract')
        // 触发新增电子合同
        showContract({})
      }
    }
  }
  onShow(() => {
    console.log('短租&长租：', props.orderType)
    init(() => {
      handleOpenNewContract()
    })
    // 获取滑动高度
    uni.getSystemInfo({
      success: function (res) {
        console.log(res.statusBarHeight)
        barHeight.value = res.statusBarHeight
      },
    })
  })
  // 复制承租方链接
  const copylink = (record, type) => {
    // 获取到链接后 复制
    getLesseeSignUrlAPI({ id: record.id }).then((res) => {
      var tlt = type == 2 ? '已将链接复制到剪切板' : '承租方作废链接已复制到剪切板'
      uni.setClipboardData({
        data: res.result,
        success: function () {
          uni.showToast({
            title: tlt,
            icon: 'none',
          })
        },
      })
    })
  }
  // 带回电话
  const addphoneFn = (recordData) => {
    // 补充电话
    if (recordData.type == 'a') {
      // 发起签署
      editClientInfo({
        id: clientData.value.id,
        clientName: clientData.value.clientName,
        mobile: recordData.phone,
        linkman: recordData.linkman,
      }).then((res) => {
        console.log('编辑企业客户接口 ---- 补充电话')
        console.log(res)
        // 判断余额
        determineAPI({ orderId: props.orderId, orderType: props.orderType == 2 ? 1 : 2 }).then((res) => {
          if (res.result.determine) {
            // 1.足够
            // 发起签署
            console.log('recordData', recordData)
            initiateFn(recordData.record)
          } else {
            // 2.不够
            uni.showModal({
              title: '提示',
              content: `账户余额不足，请先联系工作人员充值，再进行操作`,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  resetRefresh()
                }
              },
            })
            return false
          }
        })
      })
    }
    if (recordData.type == 'b') {
      // 调用发起作废补充电话的接口
      editClientInfo({
        id: clientData.value.id,
        clientName: clientData.value.clientName,
        mobile: recordData.phone,
        linkman: recordData.linkman,
      }).then((res) => {
        console.log('编辑企业客户接口 ---- 补充电话')
        console.log(res)
        // 发起作废
        nullifyFn(recordData.record)
      })
    }
    if (recordData.type == 'c') {
      editClientInfo({
        id: clientData.value.id,
        clientName: clientData.value.clientName,
        mobile: recordData.phone,
        linkman: recordData.linkman,
      }).then((res) => {
        console.log('编辑企业客户接口 ---- 补充电话')
        console.log(res)
        // 生成合同
        contractGet(recordData.record)
      })
    }
  }
  // 发起签署
  const initiateFn = (record) => {
    uni.showModal({
      title: '提示',
      content: '请确认是否要发起合同签署?',
      success: function (res) {
        if (res.confirm) {
          // 发起签署接口
          initiateAPI({ id: record.id }).then((res) => {
            console.log(res)
            // 企业/个人 提示不同
            if (record.leaseType == 1) {
              // 企业
              uni.showModal({
                title: '提示',
                content: '已将合同信息以短信的形式发送至企业联系人手机，并等待签署',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    resetRefresh()
                  }
                },
              })
            } else {
              // 个人
              uni.showModal({
                title: '提示',
                content: '已将合同信息以短信的形式发送至承租人手机，并等待签署',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    resetRefresh()
                  }
                },
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }
  // 发起作废
  const nullifyFn = (record) => {
    uni.showModal({
      title: '提示',
      content: '合同已完成签署，确认作废吗?',
      success: function (res) {
        if (res.confirm) {
          // 发起作废接口
          nullifyAPI({ id: record.id }).then((res) => {
            // 企业/个人 提示不同
            if (record.leaseType == 1) {
              // 企业
              uni.showModal({
                title: '提示',
                content: '已将作废协议以短信形式发送至企业联系人手机，并等待签署',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    resetRefresh()
                  }
                },
              })
            } else {
              // 个人
              uni.showModal({
                title: '提示',
                content: '已将作废协议以短信形式发送至承租人手机，并等待签署',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    resetRefresh()
                  }
                },
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }
  const maintenancesShow = () => {
    maintenances.value.open({ a: 1 }, props.orderId)
  }
  // 上传合同完成
  const maintenanceFn = () => {
    resetRefresh()
  }
  // 列表里点击失败原因
  const errorShow = (record) => {
    if (record.createErrorCode == 1001) {
      // 1. 姓名手机号不匹配时
      toError(record)
    } else {
      // 2. 其他原因（没有前往修改按钮）
      uni.showModal({
        title: '提示',
        content: record.createErrorReason,
        showCancel: false,
        confirmText: '关闭',
      })
    }
  }
  // 生成合同
  const contractGet = (record) => {
    createQysContractAPI({ id: record.id }).then((rees) => {
      console.log(rees)
      if (rees.result.createErrorCode) {
        if (rees.result.createErrorCode == 1001) {
          // 生成失败弹窗
          // 1. 姓名手机号不匹配时
          toError(record)
        } else {
          // 生成失败弹窗
          // 2. 其他原因（没有前往修改按钮）
          uni.showModal({
            title: '提示',
            content: rees.result.createErrorReason,
            showCancel: false,
            confirmText: '关闭',
          })
          resetRefresh()
        }
      } else if (rees.result.createErrorCode == null) {
        uni.showToast({
          title: '操作成功',
          icon: 'none',
        })
        resetRefresh()
      }
    })
  }
  // 重新生成电子合同
  const againContractGet = (record) => {
    createQysContractAPI({ id: record.id }).then((rees) => {
      console.log(rees)
      if (rees.result.createErrorCode) {
        if (rees.result.createErrorCode == 1001) {
          // 生成失败弹窗
          // 1. 姓名手机号不匹配时
          toError(record)
        } else {
          // 生成失败弹窗
          // 2. 其他原因（没有前往修改按钮）
          uni.showModal({
            title: '提示',
            content: rees.result.createErrorReason,
            showCancel: false,
            confirmText: '关闭',
          })
          resetRefresh()
        }
      } else if (rees.result.createErrorCode == null) {
        if (record.createWay == 2) {
          showContract(record)
        } else {
          uni.showToast({
            title: '操作成功',
            icon: 'none',
          })
          resetRefresh()
        }
      }
    })
  }
  // 失败弹窗
  const toError = (record) => {
    uni.showModal({
      title: '提示',
      content: '请将承租人姓名修改为上次已通过实名认证的姓名，再进行重新生成合同的操作。',
      confirmText: '前往修改',
      success: function (res) {
        if (res.confirm) {
          // 关闭当前页,跳转修改订单页面
          if (record.orderType == 1) {
            uni.navigateTo({
              url: '/pages/order/short-order/form/edit?id=' + record.orderId,
            })
          } else {
            uni.navigateTo({
              url: '/pages/order/long-order/form/edit?id=' + record.orderId,
            })
          }
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }
  // 验证手机号码格式是否正确
  const isMobile = (val) => {
    return /^[0-9]{11}$/.test(val)
  }

  // 点击新增合同传入的 record 实际上是 $event
  const showContract = (record) => {
    console.log(orderInfo.value, 'orderInfo.value.memberPhone')
    if (!isMobile(orderInfo.value.memberPhone)) {
      return uni.showToast({
        title: '承租人手机号格式不正确，请修改正确后，再生成电子合同',
        icon: 'none',
      })
    } else if (orderInfo.value.orderStatus == '10' || orderInfo.value.status == '10') {
      return uni.showToast({
        title: '请先完成订单的排车，再生成电子合同',
        icon: 'none',
      })
    } else if (orderInfo.value.orderSource == 2) {
      if (orderInfo.value.channelCarLicenseNo && !orderInfo.value.carLicenseNo) {
        uni.navigateTo({
          url: `/pages/order/contract-content/contract-verify?isOrderType=2&id=${props.orderId}&orderType=${props.orderType}`,
        })
      } else {
        if (orderInfo.value.memberType == 1) {
          let id = record && record.lesseeId ? record.lesseeId : orderInfo.value.clientId
          clientInfoDetail({ id: id }).then((res) => {
            if (!res.result.linkman || !res.result.mobile) {
              uni.navigateTo({
                url: `/pages/order/contract-content/contract-verify?isOrderType=1&id=${orderInfo.value.clientId}&orderType=${props.orderType}`,
              })
            } else {
              if (record.id) {
                uni.navigateTo({
                  url: `/pages/order/contract-content/contract-info?id=${props.orderId}&orderType=${props.orderType}&contractId=${record.id}&contractPayType=${props.contractPayType}`,
                })
              } else {
                uni.navigateTo({
                  url: `/pages/order/contract-content/contract-info?id=${props.orderId}&orderType=${props.orderType}&contractPayType=${props.contractPayType}`,
                })
              }
            }
          })
        } else {
          if (record.id) {
            uni.navigateTo({
              url: `/pages/order/contract-content/contract-info?id=${props.orderId}&orderType=${props.orderType}&contractId=${record.id}&contractPayType=${props.contractPayType}`,
            })
          } else {
            uni.navigateTo({
              url: `/pages/order/contract-content/contract-info?id=${props.orderId}&orderType=${props.orderType}&contractPayType=${props.contractPayType}`,
            })
          }
        }
      }
    } else if (orderInfo.value.memberType == 1) {
      let id = record && record.lesseeId ? record.lesseeId : orderInfo.value.clientId
      clientInfoDetail({ id: id }).then((res) => {
        if (!res.result.linkman || !res.result.mobile) {
          uni.navigateTo({
            url: `/pages/order/contract-content/contract-verify?isOrderType=1&id=${orderInfo.value.clientId}&orderType=${props.orderType}`,
          })
        } else {
          if (record.id) {
            uni.navigateTo({
              url: `/pages/order/contract-content/contract-info?id=${props.orderId}&orderType=${props.orderType}&contractId=${record.id}&contractPayType=${props.contractPayType}`,
            })
          } else {
            uni.navigateTo({
              url: `/pages/order/contract-content/contract-info?id=${props.orderId}&orderType=${props.orderType}&contractPayType=${props.contractPayType}`,
            })
          }
        }
      })
    } else {
      if (record.id) {
        uni.navigateTo({
          url: `/pages/order/contract-content/contract-info?id=${props.orderId}&orderType=${props.orderType}&contractId=${record.id}&contractPayType=${props.contractPayType}`,
        })
      } else {
        uni.navigateTo({
          url: `/pages/order/contract-content/contract-info?id=${props.orderId}&orderType=${props.orderType}&contractPayType=${props.contractPayType}`,
        })
      }
    }
  }
  const operates = ref([
    {
      label: '发起作废',
      permission: getPermission('contractInitiateCancellation'),
      show: (record) => record.contractStatus == 3,
      method: (record) => {
        if (record.leaseType == 1) {
          // 企业
          clientInfoDetail({ id: record.lesseeId }).then((res) => {
            clientData.value = res.result
            if (res.result.mobile && res.result.linkman) {
              // 1.有企业手机号
              nullifyFn(record)
            } else {
              // 2.没有企业手机号, 发起手机号填写弹窗
              addphone.value.open(record, 'b', clientData.value)
            }
          })
        } else {
          // 个人
          nullifyFn(record)
        }
      },
    },
    {
      label: '预览',
      show: (record) =>
        record.contractStatus != 9 &&
        record.contractStatus != 10 &&
        record.contractStatus != 11 &&
        record.contractStatus != -1 &&
        record.contractStatus != -2,
      permission: getPermission('contractPreview'),
      method: (record) => {
        toPreview(record)
      },
    },
    {
      // dev-ok
      label: '无需签署',
      permission: getPermission('contractNoNeedSign'),
      show: (record) => record.contractStatus == 1 || record.contractStatus == -1 || record.contractStatus == -2,
      method: (record) => {
        uni.showModal({
          title: '提示',
          content: '请确认当前合同是否无需签署，无需签署的合同将变为无效状态，并且当前合同不会重新生成',
          success: function (res) {
            if (res.confirm) {
              // 调用失效接口
              invalidAPI({ id: record.id }).then((res) => {
                console.log(res)
                // 刷新列表
                resetRefresh()
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          },
        })
      },
    },
    {
      label: '生成电子合同',
      show: (record) => record.contractStatus == -2 && handContractPermission.value,
      permission: getPermission('contractGet'),
      method: (record) => {
        console.log(record)
        uni.showModal({
          title: '提示',
          content: '电子合同生成后，修改订单或费用都不会更新此合同内的信息，请确认是否生成？',
          success: function (res) {
            if (res.confirm) {
              // 客户类型为企业客户
              if (record.leaseType == 1) {
                // 判断是否填写企业联系人的手机号
                clientInfoDetail({ id: record.lesseeId }).then((rees) => {
                  clientData.value = rees.result
                  if (rees.result.mobile && rees.result.linkman) {
                    // 1.有企业手机号
                    contractGet(record)
                  } else {
                    // 2.没有企业手机号, 发起手机号填写弹窗
                    addphone.value.open(record, 'c', clientData.value)
                  }
                })
              } else {
                // 客户类型为个人会员
                contractGet(record)
              }
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          },
        })
      },
    },
    {
      label: '重新生成',
      show: (record) => record.contractStatus == -1 && handContractPermission.value,
      permission: getPermission('contractAgain'),
      method: (record) => {
        console.log(record)
        uni.showModal({
          title: '提示',
          content: '电子合同生成后，修改订单或费用都不会更新此合同内的信息，请确认是否生成？',
          success: function (res) {
            if (res.confirm) {
              againContractGet(record)
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          },
        })
      },
    },
    {
      label: '发起签署',
      permission: getPermission('contractInitiateSigning'),
      show: (record) => record.contractStatus == 1,
      method: (record) => {
        // 客户类型为企业客户
        if (record.leaseType == 1) {
          // 判断是否填写企业联系人的手机号
          clientInfoDetail({ id: record.lesseeId }).then((res) => {
            clientData.value = res.result
            if (res.result.mobile && res.result.linkman) {
              // 1.有企业手机号
              // ①判断余额(接口判断)
              determineAPI({ orderId: props.orderId, orderType: props.orderType == 2 ? 1 : 2 }).then((res) => {
                if (res.result.determine) {
                  // 1.足够
                  initiateFn(record)
                } else {
                  // 2.不够
                  uni.showModal({
                    title: '提示',
                    content: '账户余额不足，请先联系工作人员充值，再进行操作',
                    showCancel: false,
                    success: function (res) {
                      if (res.confirm) {
                        // 无后续操作
                      }
                    },
                  })
                  return false
                }
              })
            } else {
              // 2.没有企业手机号, 发起手机号填写弹窗
              addphone.value.open(record, 'a', clientData.value)
            }
          })
        } else {
          // 客户类型为个人会员
          // 判断合同账户余额是否足够
          determineAPI({ orderId: props.orderId, orderType: props.orderType == 2 ? 1 : 2 }).then((res) => {
            if (res.result.determine) {
              // 1.足够
              initiateFn(record)
            } else {
              // 2.不够
              uni.showModal({
                title: '提示',
                content: '账户余额不足，请先联系工作人员充值，再进行操作',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    // 无后续操作
                  }
                },
              })
              return false
            }
          })
        }
      },
    },
    {
      label: '去签署',
      permission: getPermission('contractGoSigning'),
      show: (record) => record.signWay == 1 && record.contractStatus == 2 && record.lesseeSignStatus == 2 && record.hireSignStatus == 1,
      method: (record) => {
        getTenantSignUrlAPI({ id: record.id }).then((res) => {
          console.log(res)
          // 复制链接
          uni.setClipboardData({
            data: res.result,
            success: function () {
              copymodals.value.open('a')
            },
          })
        })
      },
    },
    {
      // dev-ok
      label: '撤回',
      permission: getPermission('contractWithdraw'),
      show: (record) => record.contractStatus == 2,
      method: (record) => {
        if (record.lesseeSignStatus == 1 || record.hireSignStatus == 1) {
          uni.showModal({
            title: '提示',
            content: '合同撤回后，承租方短信失效，无法完成签署，确认撤回吗？',
            success: function (res) {
              if (res.confirm) {
                revokeAPI({ id: record.id }).then(() => {
                  uni.showToast({
                    title: '操作成功',
                    icon: 'none',
                  })
                  resetRefresh()
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            },
          })
        } else if (record.orderStatus == -100 || record.orderStatus == -1000) {
          revokeAPI({ id: record.id }).then(() => {
            uni.showToast({
              title: '操作成功',
              icon: 'none',
            })
            resetRefresh()
          })
        }
      },
    },
    {
      label: '去作废',
      permission: getPermission('contractToCancel'),
      show: (record) =>
        record.signWay == 1 && record.contractStatus == 7 && record.lesseeInvalidedStatus == 2 && record.hireInvalidedStatus == 1,
      method: (record) => {
        getTenantSignUrlAPI({ id: record.id }).then((res) => {
          console.log(res)
          // 复制链接
          uni.setClipboardData({
            data: res.result,
            success: function () {
              copymodals.value.open('b')
            },
          })
        })
      },
    },
    {
      label: '维护', //仅长租
      permission: getPermission('contractMaintenance'),
      show: (record) =>
        props.orderType == 3 && record.contractAttribute == 2 && (record.contractStatus == 10 || record.contractStatus == 11),
      method: (record) => {
        console.log('record', record)
        maintenances.value.open(record, props.orderId)
      },
    },
    {
      label: '原因',
      permission: '',
      show: (record) => record.contractStatus == -1,
      method: (record) => {
        errorShow(record)
      },
    },
    {
      label: '下载',
      permission: getPermission('contract.download'),
      show: (record) => record.contractStatus == 3 || record.contractStatus == 8 || record.contractStatus == 7,
      method: (record) => {
        openPopup(record)
      },
    },
  ])

  const currenRecord = ref({})
  const openPopup = (record) => {
    currenRecord.value = record
    popupValue.value = true
  }
  const close = () => {
    popupValue.value = false
  }

  // 预览
  const toPreview = (record) => {
    downloadContractFileAPI({ id: record.id, contractFileType: 1 }).then((r) => {
      if (!r.result) {
        uni.showToast({
          title: '打开失败',
          icon: 'none',
        })
        return false
      }
      uni.downloadFile({
        url: r.result,
        success: function (res) {
          const filePath = res.tempFilePath
          uni.openDocument({
            filePath: filePath,
            success: function (res) {
              console.log('打开文档成功')
              // 销毁文件
              record.payType == 1 && deleteContractFileAPI({ contractFilePath: r.result })
            },
          })
        },
      })
    })
  }

  // 下载
  const toDownload = (record) => {
    if (!isDownload.value) {
      isDownload.value = true
      downloadContractFileAPI({ id: record.id, contractFileType: 2 }).then((r) => {
        isDownload.value = false
        if (!r.result) {
          uni.showToast({
            title: '下载失败',
            icon: 'none',
          })
          return false
        }
        uni.saveImageToPhotosAlbum({
          filePath: r.result,
          success: function () {
            uni.showToast({
              title: '已保存至相册',
              icon: 'none',
            })
            close()
          },
          fail: function (fail) {
            uni.showToast({
              title: fail.errMsg.includes('Permission') ? '无相册访问权限，无法下载' : '下载失败',
              icon: 'none',
            })
            close()
          },
        })
      })
    }
  }
</script>

<style lang="scss" scoped>
  .detail-container {
    padding: 24rpx;
  }
  .tag-person {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    view:nth-child(1) {
      max-width: 280rpx;
    }

    .person-flex-copy {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-left: 16rpx;
      .tag {
        padding: 0 16rpx;
        height: 40rpx;
        line-height: 38rpx;
        border-radius: 347rpx;
        font-size: 24rpx;
      }
      .text-no {
        background: #fff7e8;
        color: #ff7d00;
      }
      .text-yes {
        background: #e8ffea;
        color: #00b42a;
      }
    }
  }
  .copys {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .image-icon {
      width: 28rpx;
      height: 28rpx;
      margin: 0 6rpx 0 24rpx;
    }
    .copy-text {
      color: #3072f6;
      font-size: 26rpx;
      font-weight: 400;
    }
  }

  :deep(.ve-cell-content) {
    flex-wrap: wrap;
  }
  .tips {
    position: relative;
    display: flex;
    align-items: baseline;
    width: 100%;
    background: #e8f3ff;
    font-weight: 400;
    font-size: 24rpx;
    color: #1e1e1e;
    line-height: 44rpx;
    padding: 24rpx 14rpx 24rpx 64rpx;
    .img {
      position: absolute;
      top: 30rpx;
      left: 24rpx;
      width: 32rpx;
      height: 32rpx;
    }
  }
  .add-popup {
    padding: 0 40rpx 96rpx 40rpx;
    .title {
      font-weight: 600;
      font-size: 36rpx;
      color: #191c27;
      line-height: 44rpx;
      text-align: center;
      padding: 32rpx 0 48rpx 0;
    }
  }
  :deep(.ve-popup-mask) {
    background-color: rgba(0, 0, 0, 0.3);
  }
</style>
